package com.mycompany.oj.service.Impl;

import com.mycompany.oj.Mapper.Impl.MyQuestionJudgeMapperImpl;
import com.mycompany.oj.Mapper.Impl.MyTeacherMapperImpl;
import com.mycompany.oj.entity.*;
import com.mycompany.oj.service.QuestionJudgeService;
import com.mycompany.oj.util.SharedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * @author asus
 */
@Service
public class QuestionJudgeServiceImpl implements QuestionJudgeService {

    @Autowired
    MyQuestionJudgeMapperImpl questionmapper;

    @Autowired
    MyTeacherMapperImpl teach;
    @Autowired
    SharedService shaerdservice;

    @Value("${difficult.lvlOne}")
    private String lvlOne;
    @Value("${difficult.lvlTwo}")
    private String lvlTwo;
    @Value("${difficult.lvlThree}")
    private String lvlThree;

    @Value("${difficult.firstQuestionName}")
    private String firstQuestionName;

    //蓝桥杯基本题目初始化
    public List<QuestionBank> initQuestionService(String difficult) {
        String kind;
        if (difficult.equals(lvlOne)) {
            kind = "1";
        } else if (difficult.equals(lvlTwo)) {
            kind = "2";
        } else if (difficult.equals(lvlThree)) {
            kind = "3";
        } else {
            kind = "4";
        }
        List<QuestionBank> list = new ArrayList<>();
        List<Map<String, Object>> temp = questionmapper.initQuestionMapper(kind);
        for (Map<String, Object> map : temp) {
            Number num = (Number) map.get("id");
            QuestionBank questionbank = new QuestionBank(map.get("question_name").toString().substring(4), shaerdservice.getAC(num.intValue()), (String) map.get("lev"), num.intValue());
            list.add(questionbank);
        }
        return list;
    }

    //6.27改
    //具体题目初始化
    public QuestionInformation initOneQuestionService(String id) {
        QuestionInformation question_information = new QuestionInformation();
        List<Map<String, Object>> temp = questionmapper.initOneQuestionMapper(id);
        shaerdservice.mapToObject(question_information,temp.get(0));
//        question_information.setLev((String) temp.get(0).get("lev"));
//        question_information.setQuestion_name(temp.get(0).get("question_name").toString().substring(4));
//        question_information.setQuestion_text((String) temp.get(0).get("question_text"));
//        question_information.setKind((String) temp.get(0).get("type"));
        return question_information;
    }

    //蓝桥题目添加题目到收藏夹
    @Override
    public boolean favoriteService(String username, String question_id) {
        String an_id = questionmapper.getStudentId(username).get(0).get("id").toString();
        List<Map<String, Object>> iffa = questionmapper.ifFavortite(an_id, question_id);
        if (!iffa.isEmpty()) {
            return false;
        }
        List<Map<String, Object>> id = questionmapper.getFavId(an_id);
        Number num = (Number) id.get(0).get("id");

        String[] temp = questionmapper.favoriteMapper(Integer.parseInt(an_id), Integer.parseInt(question_id), Integer.parseInt(String.valueOf(num)));// new Date()为获取当前系统时间
        if (shaerdservice.check3(temp)) {
            return true;
        }
        return false;
    }

    //6.27改
    //答案页面
    public QuestionResult myresultService(String id) {
        QuestionResult temp = new QuestionResult();
        List<Map<String, Object>> temp1 = questionmapper.initOneQuestionMapper(id);
        List<Map<String, Object>> temp2 = questionmapper.resultMapper(id);
        shaerdservice.mapToObject(temp,temp1.get(0));
        shaerdservice.mapToObject(temp,temp2.get(0));

//        temp.setLev((String) temp1.get(0).get("lev"));
//        temp.setQuestion_name((String) temp1.get(0).get("question_name"));
//        temp.setQuestion_text((String) temp1.get(0).get("question_text"));
//        temp.setMemory((String) temp2.get(0).get("memory"));
//        temp.setRunning_time((String) temp2.get(0).get("running_time"));
//        temp.setResult((String) temp2.get(0).get("result"));
//        temp.setQuestion_result((String) temp2.get(0).get("question_result"));

        return temp;
    }

    //获取题目答案
    public QuestionAnswerInformation questionAnswerService(String id) {
        QuestionAnswerInformation question_Answer = new QuestionAnswerInformation();
        question_Answer.setQuestion(initOneQuestionService(id));
        //获取答案
        List<Map<String, Object>> temp = questionmapper.getQuestion(id);
        List<Map<String, Object>> myAnswer = new ArrayList<>();
        for (Map<String, Object> i : temp) {
            Map<String, Object> temp2 = new HashMap();
            temp2.put("answer", i.get("answer"));
            temp2.put("language", i.get("language"));
            temp2.put("nickname", i.get("nickname"));
            myAnswer.add(temp2);
        }
        question_Answer.setMyanswer(myAnswer);
        return question_Answer;
    }

    //获取课程题目答案
    public QuestionAnswerInformation questionCourseAnswer(String id) {
        QuestionAnswerInformation question_Answer = new QuestionAnswerInformation();
        //获取答案
        List<Map<String, Object>> temp = questionmapper.getCourseQuestionAnswer(id);

        question_Answer.setQuestion(getQuestionCourse(id));
        question_Answer.setMyanswer(temp);
        return question_Answer;
    }

    //课堂训练页面
    public List<ZhangjieInformation> studentCourseService(String username, String course_name) {
        List<Map<String, Object>> id = questionmapper.getAccountId(username);

        String accountName = String.valueOf(id.get(0).get("id"));
        List<ZhangjieInformation> list = sectionInformation(accountName, course_name);

        return list;
    }

    //判断几个实验是否完成
    private List<Map<String, Object>> judgeFinished(String course_name, String username) {
        int num;
        //判断各个实验是否完成
        List<Map<String, Object>> temp = new ArrayList<>();
        //各个实验的结果Map
        //第一个值为<0,章节数目>
        Map<String, Object> first = new HashMap<>();
        List<Map<String, Object>> number = questionmapper.getZhangjieNumber(course_name);
        if (!number.isEmpty()) {
            num = Integer.parseInt(number.get(0).get("number").toString());
            first.put("0", num);
            temp.add(first);
        } else {
            first.put("0", 0);
            temp.add(first);
            return temp;
        }
        List<Map<String, Object>> temp1 = questionmapper.haveFinishedNumber(username, course_name);
        List<Map<String, Object>> temp2 = questionmapper.totalNumber(course_name);
            if (temp2.size() != num) {
                for (int i = temp2.size(); i < num; i++) {
                    Map<String, Object> less = new HashMap<>();
                    String l = temp2.get(temp2.size() - 1).get("section_num").toString();
                    less.put("section_num", Integer.parseInt(l) + 1);
                    less.put("section_number", 0);
                    temp2.add(less);
                }
            }
            //section_num是章节号，section_number是章节完成题目数
            for (int i = 0; i < num; i++) {
                Map<String, Object> e = new HashMap<>();
                String section_num, every_course_number = "0";
                if (temp2.get(i).get("section_num") != null) {
                    section_num = temp2.get(i).get("section_num").toString();
                    every_course_number = temp2.get(i).get("section").toString();
                } else {
                    section_num = "0";
                }
                List<Map<String, Object>> t1 = temp1.stream().filter(x -> x.get("section_num").toString().equals(section_num)).collect(Collectors.toList());
                if (!t1.isEmpty()) {
                    if (t1.get(0).get("number") == temp2.get(i).get("section")) {
                        e.put(String.valueOf(Integer.parseInt(temp2.get(i).get("section_num").toString())), "success");
                    } else {
                        e.put(String.valueOf(Integer.parseInt(temp2.get(i).get("section_num").toString())), "debug");
                    }
                    temp.add(e);
                } else if (every_course_number.equals("0")) {
                    e.put(String.valueOf(Integer.parseInt(temp2.get(i).get("section_num").toString())), "success");
                    temp.add(e);
                } else {
                    e.put(String.valueOf(Integer.parseInt(temp2.get(i).get("section_num").toString())), "debug");
                    temp.add(e);
                }
            }
//        }
        return temp;
    }

    //获取章节情况
    private List<ZhangjieInformation> sectionInformation(String username, String course_name) {
        List<ZhangjieInformation> temp = new ArrayList<>();

        List<Map<String, Object>> ifFinished = judgeFinished(course_name, username);
        //本课程题目名字id
        List<Map<String, Object>> All_Question_Information = questionmapper.allQuestion(course_name);
        //时间
        List<Map<String, Object>> Last_Post_Time = questionmapper.getLastTime(username, course_name);
        //所有章节
        List<Map<String, Object>> All_Section_Information = questionmapper.getZhangjieInformation(course_name);

        //完成了哪些题目
        List<Map<String, Object>> All_Finished_Question = questionmapper.getAllPassQuestion(username);
        if (!All_Section_Information.isEmpty()) {
            //章节简介

            All_Section_Information.stream().forEach((Map<String, Object> x) -> {
                int a = 0;
                for (Map<String, Object> map : All_Section_Information) {
                    if (map.get("section_num").toString().equals(x.get("section_num").toString())) {
                        a = All_Section_Information.indexOf(map);
                    }
                }
                temp.add(new ZhangjieInformation(x.get("section_name").toString(), String.valueOf(a + 1), x.get("section_end_time").toString(), x.get("section_gogal").toString(), x.get("section_num").toString()));
            });
            for (ZhangjieInformation zhangjie_Information : temp) {
                String ppp = String.valueOf(Integer.parseInt(zhangjie_Information.getSection_num()));
                String tempp = ifFinished.get(Integer.parseInt(zhangjie_Information.getId())).get(ppp).toString();
                zhangjie_Information.setState(tempp);
                //temp.stream().forEach(x -> x.setState(tempp));
            }

            if (!All_Question_Information.isEmpty()) {
                //temp1.size()为章节数目
                for (int i = 1; i <= All_Section_Information.size(); i++) {
                    String tempi = All_Section_Information.get(i - 1).get("section_num").toString();
                    List<Map<String, String>> zhangJieQuestion = new ArrayList<>();
                    for (Map<String, Object> map : All_Question_Information.stream().filter(x -> x.get("section_num").toString().equals(tempi)).collect(Collectors.toList())) {
                        Map<String, String> e = new HashMap<>();
                        e = getEndTimeAndResult(Last_Post_Time, e, map);
                        e.put("id", map.get("id").toString());
                        e = getIfFinished(All_Finished_Question, e);
                        e.put("name", map.get("question_name").toString());
                        zhangJieQuestion.add(e);
                    }
                    temp.get(i - 1).init_zhangjie_question(zhangJieQuestion);
                }
                return temp;
            } else {
                //该章节没有题目
                return temp;
            }
        } else {
            //该课程没有章节
            ZhangjieInformation e = new ZhangjieInformation("0", "0", "0", "0", "0");
            temp.add(e);
            return temp;
        }
    }
    //

    //获取每道题的最后提交时间
    private Map<String, String> getEndTimeAndResult(List<Map<String, Object>> time_list, Map<String, String> e, Map<String, Object> map) {
        if (time_list.isEmpty()) {
            e.put("lastData", "0");
        } else if (time_list.stream().filter(x -> x.get("question_course_id") == map.get("id")).count() != 0) {
            e.put("lastDate", time_list.stream().filter(x -> x.get("question_course_id") == map.get("id")).collect(Collectors.toList()).get(0).get("last_time").toString());
        } else {
            e.put("lastDate", "0");
        }
        return e;
    }

    //获取每道题是否完成
    private Map<String, String> getIfFinished(List<Map<String, Object>> All_Finished_Question, Map<String, String> e) {
        String id = e.get("id");
        if (!All_Finished_Question.isEmpty()) {
            Stream<Map<String, Object>> a = All_Finished_Question.stream().filter(x -> x.get("Question_course_id").toString().equals(id));
            if (a.collect(Collectors.toList()).isEmpty()) {
                e.put("state", "debug");
            } else {
                e.put("state", "success");
            }
        } else {
            e.put("state", "debug");
        }
        return e;
    }

//    //获取实验测试某道题的通过率
//    private double get_course_AC(String id) {
//        List<Map<String, Object>> temp = questionMapper.calculate_course_AC(id);
//        int count1 = (int) temp.get(0).get("number");
//        if (count1 == 0) {
//            return 0;
//        }
//        int count2 = (int) temp.get(1).get("number");
//        return (double) count2 / count1;
//    }

    //总结
    @Override
    public StudentCourse summaryService(String username, String course_name) {
        StudentCourse student_course = new StudentCourse();

        String studentId = questionmapper.getAccountId(username).get(0).get("id").toString();
        if (questionmapper.getEveryQuestion(studentId, course_name).isEmpty()) {
            Map<String, Object> e = new HashMap<String, Object>();
            e.put("number", "0");
            questionmapper.getEveryQuestion(studentId, course_name).add(e);
        }
        double number, all_number;
        if (questionmapper.getEveryQuestion(studentId, course_name).isEmpty()) {
            number = 0;
        } else {
            number = Double.parseDouble(questionmapper.getEveryQuestion(studentId, course_name).get(0).get("number").toString());
        }
        if (questionmapper.getCourseNum(course_name).isEmpty()) {
            student_course.setJindu(0);
        } else {
            all_number = Double.parseDouble(questionmapper.getCourseNum(course_name).get(0).get("number").toString());
            student_course.setJindu(number / all_number);
        }
        List<Map<String, Object>> temp = questionmapper.getStudentCourseFinishedNumber(course_name, studentId);
        if (questionmapper.lastCourseAddressMapper(studentId).isEmpty()) {
//            shaerdService.mapToObject(student_course,questionMapper.getFirstId().get(0));
            student_course.setQuestion_id(questionmapper.getFirstId().get(0).get("id").toString());
            student_course.setCourse_name(questionmapper.getFirstId().get(0).get("question_name").toString());
        } else {
            student_course.setQuestion_id(questionmapper.lastCourseAddressMapper(studentId).get(0).get("question_course_id").toString());
            student_course.setCourse_name(questionmapper.lastCourseAddressMapper(studentId).get(0).get("question_name").toString());
        }
        if (questionmapper.getCoursenameEndData(student_course.getQuestion_id()).isEmpty()) {
            student_course.setCourse_name("实验一");
            List<Map<String, Object>> list = questionmapper.getFirstCourse(course_name);
            student_course.setEnd_Data(list.get(0).get("section_end_time").toString());
        } else {
            student_course.setCourse_name(questionmapper.getCoursenameEndData(student_course.getQuestion_id()).get(0).get("name").toString());
            student_course.setEnd_Data(questionmapper.getCoursenameEndData(student_course.getQuestion_id()).get(0).get("section_end_time").toString());
        }
        student_course.setQuestion_name(questionmapper.getQuestionName(student_course.getQuestion_id()).get(0).get("question_name").toString());
        if (temp.isEmpty()) {
            student_course.setPass_green(0);
        } else {
            String have_finished = temp.get(0).get("number").toString();
            List<Map<String, Object>> total_number = teach.sectionQuestionNumber(course_name);
            student_course.setPass_green((double) ((Integer.valueOf(have_finished)) / Integer.valueOf(total_number.get(0).get("number").toString())));
        }

        return student_course;
    }

    public String getLastCourse(String username) {
        String studentId = questionmapper.getAccountId(username).get(0).get("id").toString();
        if (questionmapper.getLastCourse(studentId).isEmpty()) {
            return firstQuestionName;
        }
        return questionmapper.getLastCourse(studentId).get(0).get("name").toString();
    }

    public String getShitUsername(String schoolId) {
        return questionmapper.getUsername(schoolId).get(0).get("username").toString();
    }

    //6.27改
    public QuestionInformation getQuestionCourse(String id) {
        QuestionInformation question_information = new QuestionInformation();
        shaerdservice.mapToObject(question_information,questionmapper.getCourseQuestion(id).get(0));
//        question_information.setQuestion_name(questionMapper.getCourseQuestion(id).get(0).get("question_name").toString());
//        question_information.setQuestion_text(questionMapper.getCourseQuestion(id).get(0).get("question_text").toString());
        return question_information;
    }

}
